package com.sws.worktive;

import java.util.Date;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.AppEventsLogger;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.sws.worktive.facebook.FaceBookHandler;
import com.sws.worktive.twitter.TwitterHandler;
import com.sws.worktive.util.Constant;
import com.sws.worktive.util.DialogWindow;
import com.sws.worktive.util.WT_Prefrences;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class PostScreen extends Fragment implements OnClickListener {

	Button btnPost, btnPostPhoto, btnPostDescription;
	ImageView iconWechat, iconFacebook, iconTwitter;
	LinearLayout ll_socailShare, ll_AvailablePost;
	RelativeLayout rl_txtShare;

	// TextView txtAvailablePost;

	// We chat member variable
	private IWXAPI iwxapi;

	private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
	private PendingAction pendingAction = PendingAction.NONE;
	private GraphUser user;
	private boolean canPresentShareDialog;
	private UiLifecycleHelper uiHelper;

	WT_Prefrences prefrences;

	private enum PendingAction {
		NONE, POST_PHOTO, POST_STATUS_UPDATE
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
		@Override
		public void onError(FacebookDialog.PendingCall pendingCall,
				Exception error, Bundle data) {
			Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
		}

		@Override
		public void onComplete(FacebookDialog.PendingCall pendingCall,
				Bundle data) {
			Log.d("HelloFacebook", "Success!");
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		prefrences = new WT_Prefrences(PostScreen.this.getActivity());
		if (System.currentTimeMillis() > prefrences.getLastPostTime() + 300000
				&& prefrences.getPostAvail() == 0) {
			prefrences.setPostAvail(prefrences.getPostAvail() + 1);
		}

		uiHelper = new UiLifecycleHelper(PostScreen.this.getActivity(),
				callback);
		uiHelper.onCreate(savedInstanceState);

		if (savedInstanceState != null) {
			String name = savedInstanceState
					.getString(PENDING_ACTION_BUNDLE_KEY);
			pendingAction = PendingAction.valueOf(name);
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		View view = inflater.inflate(R.layout.post_screen, container, false);

		rl_txtShare = (RelativeLayout) view.findViewById(R.id.rl_txtShare);
		ll_socailShare = (LinearLayout) view.findViewById(R.id.ll_socailShare);
		ll_AvailablePost = (LinearLayout) view
				.findViewById(R.id.ll_availablePost);

		((DrawerScreen) getActivity()).txtAvailablePost = (TextView) view
				.findViewById(R.id.txt_availPost);
		((DrawerScreen) getActivity()).txtAvailablePost.setText(" "
				+ prefrences.getPostAvail());
		btnPost = (Button) view.findViewById(R.id.btn_post);
		btnPostPhoto = (Button) view.findViewById(R.id.btn_postPhoto);
		btnPostDescription = (Button) view
				.findViewById(R.id.btn_postDescription);
		iconWechat = (ImageView) view.findViewById(R.id.icon_wechat);
		iconFacebook = (ImageView) view.findViewById(R.id.icon_fb);
		iconTwitter = (ImageView) view.findViewById(R.id.icon_twitter);
		iconWechat.setOnClickListener(this);
		iconFacebook.setOnClickListener(this);
		iconTwitter.setOnClickListener(this);
		btnPost.setOnClickListener(this);
		btnPostPhoto.setOnClickListener(this);
		btnPostDescription.setOnClickListener(this);

		regToWX();

		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		uiHelper.onResume();
		AppEventsLogger.activateApp(PostScreen.this.getActivity());
		if (appAvail) {

			WT_Prefrences prefrences = new WT_Prefrences(
					PostScreen.this.getActivity());
			prefrences.setPostAvail(prefrences.getPostAvail() + 1);
			((DrawerScreen) getActivity()).txtAvailablePost.setText(" "
					+ prefrences.getPostAvail());
			appAvail = false;
		}

	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);

		outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (pendingAction != PendingAction.NONE
				&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
			new AlertDialog.Builder(PostScreen.this.getActivity())
					.setTitle(R.string.cancelled)
					.setMessage(R.string.permission_not_granted)
					.setPositiveButton(R.string.ok, null).show();
			pendingAction = PendingAction.NONE;
		} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
			handlePendingAction();
		}
	}

	// WeChat initilization
	private void regToWX() {

		iwxapi = WXAPIFactory.createWXAPI(PostScreen.this.getActivity(),
				Constant.WECHAT_APPID, true);

		iwxapi.registerApp(Constant.WECHAT_APPID);

	}

	boolean appAvail = false;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {

		case R.id.btn_post:
			checkPrefrence();
			break;
		case R.id.btn_postPhoto:

			FragmentTransaction transaction = getChildFragmentManager()
					.beginTransaction();
			Fragment dialogFragment = getChildFragmentManager()
					.findFragmentByTag(Constant.DIALOG_FRAGMENT);
			if (dialogFragment != null) {
				transaction.remove(dialogFragment);
			}
			transaction.addToBackStack(null);

			DialogWindow dialogWindow = DialogWindow.newInstance(getResources()
					.getString(R.string.select_photo_from), "");

			dialogWindow.show(transaction, Constant.DIALOG_FRAGMENT);

			break;

		case R.id.btn_postDescription:

			((DrawerScreen) ((HomeScreen) PostScreen.this.getParentFragment())
					.getActivity()).addFragment(5);

			break;

		case R.id.icon_wechat:
			Toast.makeText(PostScreen.this.getActivity(),
					"Development under process", Toast.LENGTH_SHORT).show();

			break;

		case R.id.icon_fb:
			String message="OK worktive facebook is working";
			String logoUrl="http://carbonfreepress.gr/images/facebook.png";
			String appWebSite="https://www.facebook.com";
			
			new FaceBookHandler(message, logoUrl, appWebSite, getActivity()).sendFaceBookFeed();
			break;
		case R.id.icon_twitter:
			new TwitterHandler(getActivity()).sendTwitter("we are worktive team");
		default:
			break;
		}

	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null
				&& session.getPermissions().contains("publish_actions");
	}

	private void handlePendingAction() {
		PendingAction previouslyPendingAction = pendingAction;
		// These actions may re-set pendingAction if they are still pending, but
		// we assume they
		// will succeed.
		pendingAction = PendingAction.NONE;

		switch (previouslyPendingAction) {
		case POST_PHOTO:
			postPhoto();
			break;
		case POST_STATUS_UPDATE:
			postStatusUpdate();
			break;
		}
	}

	private interface GraphObjectWithId extends GraphObject {
		String getId();
	}

	private void postPhoto() {
		if (hasPublishPermission()) {
			Bitmap image = BitmapFactory.decodeResource(PostScreen.this
					.getActivity().getResources(), R.drawable.fb);
			Request request = Request.newUploadPhotoRequest(
					Session.getActiveSession(), image, new Request.Callback() {
						@Override
						public void onCompleted(Response response) {
							showPublishResult(getString(R.string.photo_post),
									response.getGraphObject(),
									response.getError());
						}
					});
			request.executeAsync();
		} else {
			pendingAction = PendingAction.POST_PHOTO;
		}
	}

	private void showPublishResult(String message, GraphObject result,
			FacebookRequestError error) {
		String title = null;
		String alertMessage = null;
		if (error == null) {
			title = getString(R.string.success);
			String id = result.cast(GraphObjectWithId.class).getId();
			alertMessage = getString(R.string.successfully_posted_post,
					message, id);
		} else {
			title = getString(R.string.error);
			alertMessage = error.getErrorMessage();
		}

		new AlertDialog.Builder(PostScreen.this.getActivity()).setTitle(title)
				.setMessage(alertMessage).setPositiveButton(R.string.ok, null)
				.show();
	}

	private FacebookDialog.ShareDialogBuilder createShareDialogBuilder() {
		return new FacebookDialog.ShareDialogBuilder(
				PostScreen.this.getActivity())
				.setName(getResources().getString(R.string.app_name))
				.setDescription(
						"Worktive application showcases simple Facebook integration")
				.setLink("http://developers.facebook.com/android");
	}

	private void postStatusUpdate() {
		if (canPresentShareDialog) {
			FacebookDialog shareDialog = createShareDialogBuilder().build();
			uiHelper.trackPendingDialogCall(shareDialog.present());
		} else if (user != null && hasPublishPermission()) {
			final String message = getString(R.string.status_update,
					user.getFirstName(), (new Date().toString()));

			Request request = Request.newStatusUpdateRequest(
					Session.getActiveSession(), message,
					new Request.Callback() {

						@Override
						public void onCompleted(Response response) {
							// TODO Auto-generated method stub
							showPublishResult(message,
									response.getGraphObject(),
									response.getError());
						}
					});
			request.executeAsync();
		} else {
			pendingAction = PendingAction.POST_STATUS_UPDATE;
		}
	}

	void checkPrefrence() {

		Log.v("LAST POST TIME : ", prefrences.getLastPostTime() + "");
		if (System.currentTimeMillis() > prefrences.getLastPostTime() + 300000
				|| prefrences.getPostAvail() > 0) {
			// Toast.makeText(PostScreen.this.getActivity(),
			// R.string.posting_available, Toast.LENGTH_SHORT).show();

			btnPost.setVisibility(View.GONE);
			ll_AvailablePost.setVisibility(View.GONE);
			btnPostPhoto.setVisibility(View.VISIBLE);
			btnPostDescription.setVisibility(View.VISIBLE);
			// rl_txtShare.setVisibility(View.GONE);
			// ll_socailShare.setVisibility(View.GONE);
		} else {
			Toast.makeText(PostScreen.this.getActivity(),
					R.string.posting_nt_available, Toast.LENGTH_SHORT).show();
		}
	}

}
